import { ServerDataSource } from "ng2-smart-table";
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MeiyuDataSource extends ServerDataSource {
    private _onLoadingStatus = new Subject();
    constructor(http: Http, _conf: {}) {
        super(http, _conf);
    }

    //Override supper method to handle exception gracefully.
    getElements(): Promise<any> {
        let getElementsPromise = super.getElements();
        this._onLoadingStatus.next(getElementsPromise);
        return getElementsPromise.catch((e) => {
            console.log(e);
        })
    }

    loading() {
        return this._onLoadingStatus;
    }
    //Override supper method to custom sort field
    addSortRequestOptions(requestOptions) {
        const searchParams = requestOptions.params;
        if (this.sortConf) {
            this.sortConf.forEach((fieldConf) => {
                console.log(fieldConf);
                searchParams.set(this.conf.sortFieldKey, fieldConf.field + ',' + fieldConf.direction.toUpperCase());
            });
        }
        return requestOptions;
    }

}